﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iuPlace.Core.Models;
using iuPlace.Core.Cache;

namespace iuPlace.Core.Services
{
    public class UserService : Service
    {
        public UserService(Session session)
            : base(session)
        {
        }

        public void Login(User user)
        {
            using (var context = Repositories.Context.CreateEntityFramework())
            {
                //bool isNew = false;               

                var userBD = context.Users.FirstOrDefault(o => o.UId == user.UId);
                if (userBD == null)
                {
                    //isNew = true;
                    userBD = new Repositories.User()
                    {
                        UId = user.UId,
                        Name = user.Name,
                        UserName = user.UserName,
                        ProfileUrl = user.ProfileUrl,
                        AccessToken = user.AccessToken,
                        TokenSecret = user.TokenSecret,
                        OnLine = true,
                        DateOnLine = DateTime.Now,
                        DateRegister = DateTime.Now,                     
                        Gender = (int)user.Gender,
                        DateBirthDay = DateTime.ParseExact(user.DateBirthDay, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture)
                    };

                    context.Users.AddObject(userBD);
                }
                else
                {
                    userBD.OnLine = true;
                    userBD.DateOnLine = DateTime.Now;
                }

                context.SaveChanges();

                user.Id = userBD.Id;
                user.DateBirthDay = userBD.DateBirthDay.ToString("dd/MM/yyyy");
                this.Session.IsAuthenticated = true;
                this.Session.User = user;
                
                UserCache.AddUserOnline(new UserOnline(user));
            }
        }

        public void Logout()
        {
            this.Session.IsAuthenticated = false;

            using (var context = Repositories.Context.CreateSmartContainer())
            {
                context.Update(Repositories.SCModelEntities.Table.User, new { OnLine = false }, this.Session.User.Id);
                context.Execute();
            }

            UserCache.RemoveUserOnline(this.Session.User.Id);
            this.Session.User = null;
        }
    }
}
